const bcrypt = require('bcrypt');
const Database = require('better-sqlite3');
const path = require('path');
const jwt = require('jsonwebtoken');
const db = new Database(path.join(__dirname, '../models/app.db'), { verbose: console.log });

// JWT 密钥
const JWT_SECRET = 'your-secret-key';  // 在生产环境中请更改为更安全的密钥

// 用户认证
function authenticateUser(username, password) {
  const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);

  if (user && bcrypt.compareSync(password, user.password)) {
    // 登录成功，生成 JWT token
    const token = generateToken(user);
    return {
      success: true,
      user: { username, rootPath: `/home/${username}`, currentPath: `/home/${username}` },
      token: token // 返回 token
    };
  } else {
    return { success: false };
  }
}

// 生成 JWT token
function generateToken(user) {
  const payload = {
    username: user.username,
    rootPath: `/home/${user.username}`,
    currentDir: `/home/${user.username}`
  };
  const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' }); // 设置 1 小时过期
  return token;
}

// 验证 JWT token
function verifyToken(token) {
  try {
    console.log(token,'看看token')
    
    const decoded = jwt.verify(token, JWT_SECRET);
    console.log('Decoded token:', decoded);
    return { valid: true, decoded };
  } catch (err) {
    return { valid: false, message: 'Invalid or expired token' };
  }
}

module.exports = { authenticateUser, verifyToken };





